package com.dnjn.happiness.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dnjn.happiness.system.api.domain.SysDept;
import com.dnjn.happiness.system.api.domain.SysUser;
import com.dnjn.happiness.system.domain.SysSite;
import com.dnjn.happiness.system.mapper.SysSiteMapper;
import com.dnjn.happiness.system.service.ISysDeptService;
import com.dnjn.happiness.system.service.ISysSiteService;
import com.dnjn.happiness.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.List;

/**
 * <p>
 * 站点 二级部门单拉出来做站点 服务实现类
 * </p>
 *
 * @author Amber
 * @since 2023-10-05
 */
@Service
public class SysSiteServiceImpl extends ServiceImpl<SysSiteMapper, SysSite> implements ISysSiteService {

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysDeptService deptService;

    @Override
    public void deleteSite(Long siteId) {
        baseMapper.deleteSite(siteId);
    }

    /**
     * 根据userId查询所属厂区信息
     * @param userId
     * @return
     */
    @Override
    public SysSite getSiteByUserId(Long userId) {
        SysUser sysUser = userService.selectUserById(userId);
        if (null == sysUser){
            return null;
        }
        Long deptId = sysUser.getDeptId();
        if (!ObjectUtils.isEmpty(deptId)){
            SysDept sysDept = deptService.selectDeptById(deptId);
            String ancestors = sysDept.getAncestors();
            String[] strings = ancestors.split(",");
            QueryWrapper<SysSite> queryWrapper = new QueryWrapper<SysSite>().eq("deleted", "0");
            List<SysSite> sysSiteList = baseMapper.selectList(queryWrapper);
            if (sysSiteList.size() >0 && strings.length > 0){
                for (String str : strings) {
                    for (SysSite site : sysSiteList) {
                        if (site.getDeptId().equals(Long.parseLong(str)) || site.getDeptId().equals(deptId)){
                            return site;
                        }
                    }
                }
            }
        }
        return null;
    }

    @Override
    public List<SysSite> siteAvgScore(String startTime,String endTime) {
        return baseMapper.siteAvgScore(startTime,endTime);
    }
}
